﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Jerrysjunglehuts
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                var httpContext = ((MvcApplication)sender).Context;
                var currentController = " ";
                var currentAction = " ";
                var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

                if (currentRouteData != null)
                {
                    if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                    {
                        currentController = currentRouteData.Values["controller"].ToString();
                    }

                    if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                    {
                        currentAction = currentRouteData.Values["action"].ToString();
                    }
                }

                var ex = Server.GetLastError();


                if (!(System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("\\Errors\\"))))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("\\Errors\\"));
                }
                FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("\\Errors\\errlog.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter s = new StreamWriter(fs);
                s.Close();
                fs.Close();
                FileStream fs1 = new FileStream(HttpContext.Current.Server.MapPath("\\Errors\\errlog.txt"), FileMode.Append, FileAccess.Write);
                StreamWriter s1 = new StreamWriter(fs1);
                s1.Write("Message: " + ex.Message);
                s1.Write("StackTrace: " + ex.StackTrace);
                s1.Write("InnerException: " + ex.InnerException == null ? string.Empty : ex.InnerException.Message);
                s1.Write("Date/Time: " + DateTime.Now.ToString());
                s1.Write("============================================");
                s1.Close();
                fs1.Close();

                //var controller = new ErrorController();
                var routeData = new RouteData();
                var action = "Index";

                if (ex is HttpException)
                {
                    var httpEx = ex as HttpException;
                    switch (httpEx.GetHttpCode())
                    {
                        case 404:
                            action = "NotFound";
                            break;

                        case 401:
                            action = "AccessDenied";
                            break;
                    }
                }

                httpContext.ClearError();
                httpContext.Response.Clear();
                httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
                httpContext.Response.TrySkipIisCustomErrors = true;

                routeData.Values["controller"] = "Error";
                routeData.Values["action"] = action;
                Session["Hi"] = ex.Message;
                if (ex is UnauthorizedAccessException)
                {
                    httpContext.Response.Redirect("/Home/error");
                }

                //controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);

                // ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));

            }
            catch (Exception ex)
            {
            }

        }
    }
}
